package com.bawei.databinding_recyclerview;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bawei.databinding_recyclerview.databinding.ItemBinding;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 1.自定义类继承RecyclerView.Adapter
 * 2.内部类继承RecyclerView.ViewHolder:item视图持有者
 * 3.定义ItemBinding变量并提供有参构造
 * 4。添加UserViewHoler范性并重写方法
 *
 */
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserViewHolder> {
    private List<User> mUserList;
    public UserAdapter(List<User> userList) {
        mUserList = userList;
    }
    //创建UserViewHolder
    @NonNull
    @Override
    public UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());//布局加载器
        ItemBinding itemBinding = DataBindingUtil.inflate(layoutInflater,R.layout.item,parent,false);
        return new UserViewHolder(itemBinding);
    }
    //绑定数据：设置数据源
    @Override
    public void onBindViewHolder(@NonNull UserViewHolder holder, int position) {
        holder.mItemBinding.setUser(mUserList.get(position));
    }
    //个数
    @Override
    public int getItemCount() {
        return mUserList.size();
    }

    class UserViewHolder extends RecyclerView.ViewHolder{
        ItemBinding mItemBinding;//数据绑定

        public UserViewHolder( ItemBinding itemBinding) {
            super(itemBinding.getRoot());//getRoot获得itemBinding对应的view
            mItemBinding = itemBinding;
        }

        public UserViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }


}
